import json
import urllib
import urllib.request, urllib.error, urllib.parse


class CLMessageSend:

    def __init__(self, configs):

        self.account = configs['account']

        self.password = configs['password']

        self.host = configs['host']

        self.sms_send_uri = configs['sms_send_uri']

        self.port = configs['port']

    def send_sms(self, text, phone):
        params = {'account': self.account, 'password': self.password, 'msg': urllib.request.quote(text), 'phone': phone,
                  'report': 'false'}
        params = json.dumps(params)
        headers = {"Content-type": "application/json"}
        return self.__http_post(self.sms_send_uri, params, headers, self.host)

    def variable_send_sms(self, text, phone, variable):
        params = {'account': self.account, 'password': self.password, 'msg': text,
                  'report': 'false', 'params': phone+","+variable}
        params = json.dumps(params)
        headers = {"Content-type": "application/json"}
        return self.__http_post(self.sms_send_uri, params, headers, self.host)

    def __http_post(self, url, para, headers, host):
        data = bytes(para, 'utf8')
        req = urllib.request.Request(url, headers=headers, origin_req_host=host, data=data)
        with urllib.request.urlopen(req) as f:
            resp = f.read()
            return eval(resp)